<template>
  <div
    style="-webkit-overflow-scrolling: touch"
    class="bg-[url('~/assets/img/img_map1.png')] bg-fixed bg-top bg-cover bg-no-repeat h-[calc(100vh-6.05rem)] !overflow-hidden flex flex-col justify-center items-center gap-10"
  >
    <div class="bg-white rounded-lg p-5 flex flex-col gap-5 shadow-[0px_16px_48px_0px_rgba(0,0,0,0.24)] w-[90%] lg:w-1/2 md:w-1/2 xl:w-1/3">
      <!-- 国家-->
      <div class="flex flex-col gap-2">
        <span class="text-xs font-medium text-gray-600">
          {{ $t('formItem.countryRegion') }}
        </span>
        <el-select
          class="input"
          filterable
          value-key="iso"
          @change="countryChange"
          v-model="userSelectInfo.regions"
          :placeholder="$t('formPlaceholder.select')"
          @focus="handleSelectClick"
          @hook:mounted="handleSelectClick"
          @visible-change="handleSelectClick"
        >
          <template slot="prefix">
            <img
              class="overflow-hidden w-4 h-4 rounded-full"
              v-if="userSelectInfo.regions.icon"
              v-lazy="$globalFn.imgPrefixUrl(userSelectInfo.regions.icon, 'national_flag')"
              loading="lazy"
              :alt="'Selected country flag - ' + userSelectInfo.regions.iso"
              :title="'Country flag - ' + userSelectInfo.regions.iso"
            />
            <img
              v-else
              class="w-4 h-4"
              src="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
              alt="Default language icon"
              title="Default language selection"
              loading="lazy"
            />
          </template>
          <el-option v-for="item in regionsList" :key="item.id" :label="item.name" :value="item" class="flex items-center">
            <div class="flex items-center">
              <img
                class="mr-2 w-6 h-6 rounded-full"
                v-lazy="$globalFn.imgPrefixUrl(item.icon, 'national_flag')"
                :alt="'Flag of ' + item.name"
                :title="'National flag - ' + item.name"
                loading="lazy"
              />
              <span class="text-sm font-medium capitalize">
                {{ item.name }}
              </span>
            </div>
          </el-option>
        </el-select>
      </div>
      <!-- 语言 -->
      <div class="flex flex-col gap-2">
        <span class="text-xs font-medium text-gray-600">
          {{ $t('formItem.lange') }}
        </span>
        <el-select
          class="input"
          filterable
          v-model="userSelectInfo.language_code"
          :placeholder="$t('formPlaceholder.select')"
          @focus="handleSelectClick"
          @hook:mounted="handleSelectClick"
          @visible-change="handleSelectClick"
        >
          <template slot="prefix">
            <img
              class="w-4 h-4"
              src="https://cd.sealmg.com/assets/img/set-plane-lange.png"
              alt="Language selection icon"
              title="Select language"
              loading="lazy"
            />
          </template>
          <el-option v-for="(val, key) in languageObj" :key="key" :label="val" :value="key"> </el-option>
        </el-select>
      </div>
      <!-- 货币 -->
      <div class="flex flex-col gap-2">
        <span class="text-xs font-medium text-gray-600">
          {{ $t('formItem.currency') }}
        </span>
        <el-select
          class="input"
          filterable
          v-model="userSelectInfo.currency_code"
          :placeholder="$t('formPlaceholder.select')"
          @focus="handleSelectClick"
          @hook:mounted="handleSelectClick"
          @visible-change="handleSelectClick"
        >
          <template slot="prefix">
            <img
              class="w-4 h-4"
              src="https://cd.sealmg.com/assets/img/set-plane-currency.png"
              alt="Currency selection icon"
              title="Select currency"
              loading="lazy"
            />
          </template>
          <el-option v-for="(item, index) in currencyList" :key="index" :label="item.currency_name" :value="item.currency_code"> </el-option>
        </el-select>
      </div>
      <button @click="sureSelect" class="flex gap-4 justify-center items-center py-3 mt-6 bg-[#FF4E33] rounded-full">
        <span class="text-lg font-medium text-white">
          {{ $t('formBtn.confirm') }}
        </span>
      </button>
    </div>
    <div></div>
    <!-- <   ref="loading" /> -->
  </div>
</template>
<script>
  export default {
    name: 'LanguageCurrency',
    layout: 'newsHome',
    data() {
      return {
        // 用户选择的信息对象
        userSelectInfo: {
          currency_code: '', // 货币代码
          language_code: '', // 语言代码
          regions: '' // 地区信息
        }
      }
    },
    fetch({ store }) {
      store.commit('setHeaderVisibility', true) // 显示头部
      store.commit('setFooterVisibility', false) // 隐藏底部
    },
    // 离开页面 setFooterVisibility 为 true
    beforeRouteLeave(to, from, next) {
      this.$store.commit('setFooterVisibility', true)
      next()
    },
    created() {
      this.handleSelectClick()
      // this.$nextTick(() => {
      //   document.querySelectorAll(".el-input__inner").forEach((input) => {
      //     input.removeAttribute("readonly");
      //   });
      // });
    },
    watch: {
      regionsList: {
        handler(newVal) {
          if (newVal && newVal.length > 0) {
            this.setDefault()
          }
        },
        immediate: true
      }
    },
    computed: {
      // 语言列表
      languageObj() {
        return this.$store?.state?.initData?.language || {}
      },
      // 货币列表
      currencyList() {
        return Object.values(this.$store?.state?.initData?.currencies || {})
      },
      // 国家列表
      regionsList() {
        return this.$store?.state?.initData?.regions || []
      }
    },
    methods: {
      handleSelectClick(e) {
        if (process.client) {
          this.$nextTick(() => {
            setTimeout(() => {
              document.querySelectorAll('.el-input__inner').forEach(input => {
                input.removeAttribute('readonly')
              })
            }, 200)
          })
        }
      },
      // 确认选择
      async sureSelect() {
        try {
          this.$nuxt.$loading.start()
          const { regions, language_code, currency_code } = this.userSelectInfo
          // 验证必填项
          if (!regions || !language_code || !currency_code) {
            this.$message.error('请完成所有必填项选择')
            return
          }
          // 设置语言和用户选择信息
          // this.$i18n.setLocale(language_code);
          this.$cookies.set('userSelect', {
            country_icon: regions.icon,
            language_code,
            country_code: regions.iso,
            currency_code
          })
          const redirectPath = decodeURIComponent(this.$route.query.redirect) || '/'
          // 根据语言构建重定向路径
          const finalPath = language_code !== 'en' ? `/${language_code}${redirectPath}` : redirectPath
          // 第一种
          const link = document.createElement('a')
          link.href = finalPath
          link.target = '_self' // 或 '_self' 根据需求
          link.style.display = 'none'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          // 第二种
          //window.location.href = finalPath;
          // 第三种
          // this.$router.push({
          //   path: finalPath,
          // });
          // this.$store.commit("user/setkey", new Date().getTime());
          // this.$message.success('切换成功')
        } catch (error) {
          console.error('切换语言/货币失败:', error)
          // this.$message.error('操作失败，请重试')
        } finally {
          this.$nuxt.$loading.finish()
        }
      },
      // 国家/地区变更时更新语言和货币设置
      countryChange(region) {
        if (!region) return
        const { language_code, currency_code } = region
        Object.assign(this.userSelectInfo, {
          language_code,
          currency_code
        })
      },
      // 设置默认值
      setDefault() {
        const userSelect = this.$cookies.get('userSelect') || {
          country_icon: '/flag/United%20States.png',
          country_code: 'US',
          currency_code: 'USD',
          language_code: this.$i18n.locale
        }
        const { language_code, currency_code, country_code } = userSelect
        Object.assign(this.userSelectInfo, {
          language_code,
          currency_code,
          regions: this.regionsList.find(item => item.iso === country_code) || {}
        })
      }
    }
  }
</script>
<style lang="less" scoped>
  /deep/ .el-input__prefix {
    width: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  /deep/ .el-input--prefix .el-input__inner {
    padding-left: 40px;
  }
  :deep(.el-select-dropdown__wrap) {
    .el-select-dropdown__item {
      display: flex !important;
      align-items: center !important;
    }
  }
</style>
